package com.summer.data.sqlite;

import com.summer.data.Jsql;
import com.summer.data.connection.*;
//import com.summer.data.connection.SessionTransactionManager;
//import com.summer.data.connection.TransactionManager;
import com.summer.data.connection.source.DataSourceSessionFactory;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.Before;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author
 * @description
 */
public class SqliteDb {

    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    private static final File DATABASE_FILE = new File("summer_data.db");

    protected HikariDataSource dataSource = new HikariDataSource();

    protected SessionFactory sessionFactory = null;

    protected Session session;

    protected Transaction transaction;

    @Before
    public void prepareEnv() throws SQLException, IOException {
        if (DATABASE_FILE.exists()) DATABASE_FILE.delete();

        dataSource.setJdbcUrl("jdbc:sqlite:./" + DATABASE_FILE.getName());
        dataSource.setDriverClassName("org.sqlite.JDBC");
        dataSource.setMaximumPoolSize(1);

        sessionFactory = new DataSourceSessionFactory(dataSource);
        session = sessionFactory.openSession();

        TransactionDef transactionDef = new TransactionDef();
        transactionDef.isolation = TransactionDef.ISOLATION.READ_UNCOMMITTED;
        transaction = sessionFactory.openTransactional(transactionDef);

        SqliteFile sqlFile = new SqliteFile("/sqlite.sql");

        for(String sql : sqlFile.getSqls()){
            if(!isEmpty(sql)) {
                Jsql jsql = new Jsql(sql);
                session.executeUpdate(jsql);
            }
        }

    }

}
